﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServerLibrary.Abstract;
using System.Web;
using System.Net;
using ServerLibrary.Infrastructure;
using System.IO;
namespace ServerLibrary.Concrete
{
    /// <summary>
    /// TODO: Implements communicator.
    /// </summary>
    public class Communicator : ICommunicator
    {
        /// <summary>
        ///  Contains HttpListener for listening incoming http requests
        /// </summary>
        private HttpListener httpListener = new HttpListener();
        
        /// <summary>
        /// Contains TaskManager for getting tasks
        /// </summary>
        private ITaskManager taskManager = new TaskManager();
        
        /// <summary>
        /// Contains TaskHandler,which set task in queue
        /// </summary>
        private ITaskHandler taskHandler = new TaskHandler();
        
        /// <summary>
        /// Contains object with server configurations
        /// </summary>
        private IConfigurator configurator = new Configurator();

        /// <summary>
        /// Default constructor
        /// </summary>
        public Communicator()
        {
        }
        
        /// <summary>
        /// Constructs communicator with params
        /// </summary>
        /// <param name="httpListener">HttpListener for listening requests</param>
        /// <param name="taskManager">TaskManager for getting task</param>
        /// <param name="taskHandler">TaskHandler which set task in queue</param>
        /// <param name="configurator"></param>
        public Communicator(HttpListener httpListener,ITaskManager taskManager,ITaskHandler taskHandler,IConfigurator configurator)
        {
            this.httpListener = httpListener;
            this.taskManager = taskManager;
            this.taskHandler = taskHandler;
            this.configurator = configurator;
        }
        
       
        public void Start()
        {
            httpListener.Prefixes.Add("http://+:11000/");
            httpListener.Start();
            Console.WriteLine("HttpServer v 1.0\nwaiting for requests.....");
            taskHandler.TaskFinished += new Infrastructure.TaskFinishedHandler(OnTaskFinished);
            while (true)
            {
                taskHandler.AddTask(taskManager.GetTask(httpListener.GetContext()));
               
            }
        }
       
        
        public void Stop()
        {
            httpListener.Stop();
        }
        
        /// <summary>
        /// Event which raises when task finished
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="arguments"></param>
        void OnTaskFinished(object sender, TaskHandlerEventArguments arguments)
        {
           
        }
    }
}
